package cz.semjob.learning.classifier.benchmark;

import java.io.File;
import java.io.IOException;
import java.util.Date;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import cz.semjob.learning.classifier.io.ClassifierIO;
import cz.semjob.learning.data.TaxonomyLearningException;

@Component
public class ClassifierBenchmarkResultsIO {

	@Autowired
	private ClassifierIO classifierIO;

	private static Logger logger = Logger
			.getLogger(ClassifierBenchmarkResultsIO.class);

	public void writeBenchmarkResults(ClassifierBenchmarkResults results,
			String rootDirectoryPath) throws IOException,
			TaxonomyLearningException {
		Date now = new Date();
		final String name = results.getName();
		File rootDirectory = new File(rootDirectoryPath);
		if (!rootDirectory.isDirectory()) {
			throw new IOException("Root directory is not a directory: "
					+ rootDirectoryPath);
		}

		File directory = new File(rootDirectoryPath + File.separator + name
				+ File.separator + results.getClassifierInfo() + File.separator
				+ now.getTime());
		logger.info("Writing results to directory: "
				+ directory.getAbsolutePath());
		if (directory.mkdirs()) {
			String resultsString = results.toPrettyString();
			String infoString = results.toInfoString();
			FileUtils.writeStringToFile(new File(directory.getAbsolutePath()
					+ File.separator + "results.txt"), resultsString);
			FileUtils.writeStringToFile(new File(directory.getAbsolutePath()
					+ File.separator + "info.properties"), infoString);
			classifierIO.exportClassifierToFile(directory.getAbsolutePath()
					+ File.separator + "classifier.object",
					results.getClassifier());
			classifierIO.exportTextInstanceCreatorToFile(
					directory.getAbsolutePath() + File.separator
							+ "instanceCreator.object",
					results.getInstanceCreator());
			// classifierIO.exportClassifierBenchmarkResultsToFile(
			// directory.getAbsolutePath() + File.separator
			// + "results.object", results);
		} else {
			throw new IOException("Could not create result directory: "
					+ directory);

		}

	}

	public void setClassifierIO(ClassifierIO classifierIO) {
		this.classifierIO = classifierIO;
	}
}
